package go_redis

import (
	"errors"
	"github.com/go-redis/redis"
	"time"
)

type RedisConfig struct {
	Addr         string        `toml:"addr"`
	Password     string        `toml:"password"`
	DB           int           `toml:"db"`
	MaxRetries   int           `toml:"max_retries"`
	DialTimeout  time.Duration `toml:"dail_timeout"`
	ReadTimeout  time.Duration `toml:"read_timeout"`
	WriteTimeout time.Duration `toml:"write_timeout"`
	PoolSize     int           `toml:"pool_size"`
	PoolTimeout  time.Duration `toml:"pool_timeout"`
}

func InitRedis(cfg RedisConfig) (*redis.Client, error) {
	if len(cfg.Addr) == 0 {
		return nil, errors.New("redis addr is null")
	}
	opt := &redis.Options{
		Addr:         cfg.Addr,
		Password:     cfg.Password,
		DB:           cfg.DB,
		MaxRetries:   cfg.MaxRetries,
		DialTimeout:  cfg.DialTimeout,
		ReadTimeout:  cfg.ReadTimeout,
		WriteTimeout: cfg.WriteTimeout,
		PoolSize:     cfg.PoolSize,
		PoolTimeout:  cfg.PoolTimeout,
	}

	redisClient := redis.NewClient(opt)
	_, err := redisClient.Ping().Result()
	if err != nil {
		return nil, err
	}
	return redisClient, nil
}
